import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
<<<<<<< HEAD
import { loginApi, registerApi, getUserInfoApi } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const permissions = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.username || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')
  const userRole = computed(() => userInfo.value?.role || 'user')

  // 登录
  const login = async (loginForm) => {
    try {
      const response = await loginApi(loginForm)
      const { token: accessToken, userInfo: info } = response.data

      // 保存token
      token.value = accessToken
      localStorage.setItem('token', accessToken)

      // 保存用户信息
      userInfo.value = info
      localStorage.setItem('userInfo', JSON.stringify(info))

      // 设置用户类型为商家
      localStorage.setItem('userType', 'merchant')

      return response
    } catch (error) {
=======
import { login as loginApi, register as registerApi, getUserInfo as getUserInfoApi } from '@/api/auth'
import { getMerchantOverview, getMerchantTransaction } from '@/api/dashboard'
import { registerMerchant as registerMerchantApi } from '@/api/merchant'

export const useUserStore = defineStore('user', () => {
  // 商家认证状态
  const token = ref(localStorage.getItem('merchant_token') || '')
  const merchantInfo = ref(null)
  const merchantStatus = ref(localStorage.getItem('merchant_status') || '') // pending, approved, rejected

  // 商家业务数据
  const businessData = ref({
    creditScore: 0,        // 信用分数
    completionRate: 0,     // 完成率
    goodReviewRate: 0,     // 好评率
    refundRate: 0,         // 退款率
    averageProcessTime: 0, // 平均处理时间(小时)
    totalOrders: 0,        // 总订单数
    monthlyRevenue: 0,     // 月收入
    availableBalance: 0,   // 可提现余额
    frozenBalance: 0,      // 冻结金额
    pendingBalance: 0      // 在途金额(14天结算期)
  })

  // 商家设置
  const merchantSettings = ref({
    autoAcceptOrders: false,     // 自动接单
    maxDistance: 5,              // 最大接单距离(km)
    minOrderAmount: 0,           // 最小接单金额
    workingHours: {              // 工作时间
      start: '08:00',
      end: '20:00'
    },
    serviceAreas: [],            // 服务区域
    autoWithdraw: false,         // 自动提现
    withdrawThreshold: 1000      // 自动提现阈值
  })

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isMerchantApproved = computed(() => merchantStatus.value === 'approved')
  const isMerchantPending = computed(() => merchantStatus.value === 'pending')
  const isMerchantRejected = computed(() => merchantStatus.value === 'rejected')
  const merchantName = computed(() => merchantInfo.value?.name || '')
  const merchantPhone = computed(() => merchantInfo.value?.phone || '')

  // 风控状态
  const isHighRisk = computed(() => {
    return businessData.value.refundRate > 15 || businessData.value.goodReviewRate < 80
  })

  // 是否需要人工审核提现
  const needManualWithdrawReview = computed(() => {
    return businessData.value.refundRate > 15 || businessData.value.goodReviewRate < 70
  })

  // 信用等级
  const creditLevel = computed(() => {
    const score = businessData.value.creditScore
    if (score >= 90) return { level: 'excellent', label: '优秀', color: '#67C23A' }
    if (score >= 80) return { level: 'good', label: '良好', color: '#409EFF' }
    if (score >= 70) return { level: 'normal', label: '一般', color: '#E6A23C' }
    if (score >= 60) return { level: 'poor', label: '较差', color: '#F56C6C' }
    return { level: 'bad', label: '差', color: '#F56C6C' }
  })

  // 商家登录
  const login = async (loginForm) => {
    try {
      const response = await loginApi(loginForm)

      if (response.code === 200 && response.data) {
        const { token: accessToken, userInfo } = response.data

        // 保存认证信息
        token.value = accessToken
        merchantInfo.value = userInfo
        merchantStatus.value = 'approved' // 默认已认证状态

        // 保存到localStorage
        localStorage.setItem('token', accessToken)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        localStorage.setItem('merchant_status', 'approved')

        // 获取商家业务数据
        await loadBusinessData()

        return response
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      // 如果是开发环境且API不可用，使用模拟数据
      if (import.meta.env.DEV && error.message.includes('Network Error')) {
        console.warn('API不可用，使用模拟数据')
        return simulateLogin()
      }
>>>>>>> c61637f (所有前后端正常登录)
      throw error
    }
  }

  // 注册
  const register = async (registerForm) => {
    try {
      const response = await registerApi(registerForm)
      return response
    } catch (error) {
      throw error
    }
  }

<<<<<<< HEAD
=======
  // 商家注册
  const registerMerchant = async (registerForm) => {
    try {
      const response = await registerMerchantApi(registerForm)
      return response
    } catch (error) {
      throw error
    }
  }

>>>>>>> c61637f (所有前后端正常登录)
  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await getUserInfoApi()
      userInfo.value = response.data
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      return response
    } catch (error) {
      throw error
    }
  }

<<<<<<< HEAD
  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userType')
  }

  // 初始化用户信息
  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
=======
  // 模拟登录（开发环境使用）
  const simulateLogin = () => {
    const mockData = {
      token: 'mock_token_' + Date.now(),
      merchantInfo: {
        id: 1,
        name: '',
        phone: '',
        email: '',
        address: '',
        businessLicense: '',
        registrationDate: '',
        status: 'pending'
      },
      merchantStatus: 'pending',
      businessData: {
        creditScore: 0,
        completionRate: 0,
        goodReviewRate: 0,
        refundRate: 0,
        averageProcessTime: 0,
        totalOrders: 0,
        monthlyRevenue: 0,
        availableBalance: 0,
        frozenBalance: 0,
        pendingBalance: 0
      }
    }

    token.value = mockData.token
    merchantInfo.value = mockData.merchantInfo
    merchantStatus.value = mockData.merchantStatus
    businessData.value = { ...businessData.value, ...mockData.businessData }

    localStorage.setItem('merchant_token', mockData.token)
    localStorage.setItem('merchant_info', JSON.stringify(mockData.merchantInfo))
    localStorage.setItem('merchant_status', mockData.merchantStatus)

    return Promise.resolve({ data: mockData })
  }

  // 加载业务数据
  const loadBusinessData = async () => {
    try {
      // 获取概览数据
      const overviewResponse = await getMerchantOverview()
      if (overviewResponse.code === 200) {
        const overview = overviewResponse.data
        businessData.value = {
          ...businessData.value,
          totalOrders: overview.totalOrders || 0,
          creditScore: overview.creditScore || 0,
          completionRate: overview.completionRate || 0,
          goodReviewRate: overview.goodReviewRate || 0,
          refundRate: overview.refundRate || 0,
          averageProcessTime: overview.averageProcessTime || 0
        }
      }

      // 获取交易数据
      const transactionResponse = await getMerchantTransaction()
      if (transactionResponse.code === 200) {
        const transaction = transactionResponse.data
        businessData.value = {
          ...businessData.value,
          monthlyRevenue: transaction.monthlyRevenue || 0,
          availableBalance: transaction.availableBalance || 0,
          frozenBalance: transaction.frozenBalance || 0,
          pendingBalance: transaction.pendingBalance || 0
        }
      }
    } catch (error) {
      console.warn('加载业务数据失败，使用默认值:', error)
      // 使用默认空数据
      businessData.value = {
        creditScore: 0,
        completionRate: 0,
        goodReviewRate: 0,
        refundRate: 0,
        averageProcessTime: 0,
        totalOrders: 0,
        monthlyRevenue: 0,
        availableBalance: 0,
        frozenBalance: 0,
        pendingBalance: 0
      }
    }
  }

  // 获取商家信息
  const getMerchantInfo = async () => {
    try {
      const response = await getUserInfoApi()
      if (response.code === 200) {
        merchantInfo.value = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))

        // 同时加载业务数据
        await loadBusinessData()
      }
      return response
    } catch (error) {
      throw error
    }
  }

  // 更新商家设置
  const updateMerchantSettings = (settings) => {
    merchantSettings.value = { ...merchantSettings.value, ...settings }
    // 这里应该调用API保存设置
    return Promise.resolve({ success: true })
  }

  // 登出
  const logout = () => {
    token.value = ''
    merchantInfo.value = null
    merchantStatus.value = ''
    businessData.value = {
      creditScore: 0,
      completionRate: 0,
      goodReviewRate: 0,
      refundRate: 0,
      averageProcessTime: 0,
      totalOrders: 0,
      monthlyRevenue: 0,
      availableBalance: 0,
      frozenBalance: 0,
      pendingBalance: 0
    }

    // 清除localStorage
    localStorage.removeItem('merchant_token')
    localStorage.removeItem('merchant_info')
    localStorage.removeItem('merchant_status')
  }

  // 初始化商家信息
  const initMerchantInfo = () => {
    const savedMerchantInfo = localStorage.getItem('merchant_info')
    if (savedMerchantInfo) {
      try {
        merchantInfo.value = JSON.parse(savedMerchantInfo)
      } catch (error) {
        console.error('解析商家信息失败:', error)
>>>>>>> c61637f (所有前后端正常登录)
        logout()
      }
    }
  }

<<<<<<< HEAD
  // 更新用户信息
  const updateUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    return userRole.value === role
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 计算属性
    isLoggedIn,
    userName,
    userAvatar,
    userRole,
    
    // 方法
    login,
    register,
    getUserInfo,
    logout,
    initUserInfo,
    updateUserInfo,
    hasPermission,
    hasRole
=======
  return {
    // 状态
    token,
    merchantInfo,
    merchantStatus,
    businessData,
    merchantSettings,

    // 计算属性
    isLoggedIn,
    isMerchantApproved,
    isMerchantPending,
    isMerchantRejected,
    merchantName,
    merchantPhone,
    isHighRisk,
    needManualWithdrawReview,
    creditLevel,

    // 方法
    login,
    register,
    registerMerchant,
    simulateLogin,
    loadBusinessData,
    getMerchantInfo,
    updateMerchantSettings,
    logout,
    initMerchantInfo
>>>>>>> c61637f (所有前后端正常登录)
  }
}) 